/**  
* @author: suan@unibroad.com
* @date 2014年5月6日 下午12:48:28
* @Copyright: 2014 unibroad.com Inc. All rights reserved.
*/
package com.strugglerz.web.base.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * @Title: MappingFastjsonHttpMessageConverter.java
 * @Package com.unibroad.appstore.util
 * @Description:
 * @version V1.0
 */
public class MappingFastjsonHttpMessageConverter extends AbstractHttpMessageConverter<Object> {

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private SerializerFeature[] serializerFeature;

    /** 线程上文设置是否加密输出 */
    private ThreadLocal<Boolean> encryptOutputHolder = new ThreadLocal<>();

    public SerializerFeature[] getSerializerFeature() {
        return serializerFeature;
    }

    public void setSerializerFeature(SerializerFeature[] serializerFeature) {
        this.serializerFeature = serializerFeature;
    }

    public MappingFastjsonHttpMessageConverter() {
        super(new MediaType("application", "json", DEFAULT_CHARSET));
    }

    @Override
    public boolean canRead(Class<?> clazz, MediaType mediaType) {
        return true;
    }

    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        return true;
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        throw new UnsupportedOperationException();
    }

    @Override
    protected void writeInternal(Object o, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {

        String jsonString = JSON.toJSONString(o, serializerFeature);

        OutputStream out = outputMessage.getBody();
        if (encryptOutputHolder.get() == Boolean.TRUE) {
            // 用完一次就清除一次
            encryptOutputHolder.remove();
            out.write(EncryptTool.getEncryptResult(jsonString).getBytes(DEFAULT_CHARSET));
        } else {
            out.write(jsonString.getBytes(DEFAULT_CHARSET));
        }
        out.flush();
    }

    @Override
    protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException {
        byte[] byteArr = new byte[] {};
        inputMessage.getBody().read(byteArr);
        return JSON.parseObject(byteArr, clazz);
    }

    /**
     * @param encryptOutput
     *            to set - {参数含义描述}.
     */
    public void setEncryptOutput(boolean encryptOutput) {
        encryptOutputHolder.set(encryptOutput);
    }

}